/*
 * @FileName: app_mppt.c
 * @Author: GreyQiu qiushaogui@aikosolar.com
 * @Date: 2023-08-08 17:15:11
 * @LastEditors: GreyQiu qiushaogui@aikosolar.com
 * @LastEditTime: 2023-09-14 11:30:47
 * @Description: 
 * 
 * Copyright (c) 2023, All Rights Reserved. 
 */

#include "mppt.h"
#include "app_mppt.h"
#include <string.h>
#include "app_analog.h"
#include "loop.h"

#define MPPT_NUM    2
// mppt数组，参数直接在数组中初始化
mppt_t mppt[MPPT_NUM] = 
{
    // mppt1
    {.id = 0, .state = 0, .loop =  &(vin_loop), .out = 1.02, .outMax = 1.02f, .outMin = 0.0f, .pwr_pre = 0,
     .step = 0.01f, .stepMax = 0.02f, .stepMin = 0.001f, .stepGrad = 0.001, .vin_addr = ANALOG_VALUE_ADDR_VIN, .iin_addr = ANALOG_VALUE_ADDR_IIN},

    {.id = 1, .state = 0, .loop = &(vin_loop), .out = 66.5f, .outMax = 100.0f, .outMin = 19.0f, .pwr_pre = 0,
     .step = 0.8f, .stepMax = 1.0f, .stepMin = 0.6f, .stepGrad = 0.1f, .vin_addr = ANALOG_VALUE_ADDR_VIN, .iin_addr = ANALOG_VALUE_ADDR_IIN}
};

void app_mppt_run(uint8_t mppt_id)
{
    mppt_handle(&mppt[mppt_id]);
}

void app_mppt_enable(uint8_t mppt_id)
{
    mppt[mppt_id].state = MPPT_STATE_TRACK;
}

void app_mppt_disable(uint8_t mppt_id)
{
    mppt[mppt_id].state = MPPT_STATE_DISABLE;
}

void app_mppt_init(uint8_t mppt_id, float Voc, float ref)
{
    mppt[mppt_id].dir[0] = 1;
    mppt[mppt_id].voc = Voc;
    mppt[mppt_id].outMax = Voc + MPPT_VOC_OFFSET; // 会引发带载切换大曲线可能追不到最大点，因为MPPT范围最大为outMax
    mppt[mppt_id].out = ref;
    mppt[mppt_id].loop->ref = mppt[mppt_id].out;
    mppt[mppt_id].cnt_step = 0;
    mppt[mppt_id].cnt_delay = 0;
    mppt[mppt_id].cnt_prescale = 0;
    mppt[mppt_id].div = MPPT_PERIOD / 10;
}

void app_mppt_restart(uint8_t mppt_id)
{
    mppt[mppt_id].dir[0] = 1;
    mppt[mppt_id].out = mppt[mppt_id].voc * 0.95f;
    mppt[mppt_id].loop->ref = mppt[mppt_id].out;
}

float app_mppt_get_ref(uint8_t mppt_id)
{
    return mppt[mppt_id].out;
}

uint8_t app_mppt_get_state(uint8_t mppt_id)
{
    return mppt[mppt_id].state;
}
